package package1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class TestForSequenceInputStream {
	/**
	 *  merging multiple stream to a whole one, there would no -1 returned until all streams finished reading
	 * @throws IOException
	 */
	public TestForSequenceInputStream() throws IOException {
		sequenceInputStreamTest1();
		sequenceInputStreamTest2();
		sequenceInputStreamTest3();
	}
	private void sequenceInputStreamTest3() throws IOException {
		ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
		for(int i=97;i<100;i++) list.add(new FileInputStream((char)i+".txt"));
		Enumeration<FileInputStream> e = Collections.enumeration(list);
		SequenceInputStream sis = new SequenceInputStream(e);
		FileOutputStream fos = new FileOutputStream("d3.txt"); 
		byte []buf = new byte[1024]; int len ;
		while((len = sis.read(buf))!=-1)fos.write(buf,0,len);
		fos.close();sis.close();
		System.err.println("succeed");
	}
	private static void sequenceInputStreamTest2() throws IOException {
		ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
		for(int i=97;i<100;i++) list.add(new FileInputStream((char)i+".txt"));
		final Iterator<FileInputStream> ite = list.iterator();	
		Enumeration<FileInputStream> e = new Enumeration<FileInputStream>() {
			public FileInputStream nextElement() {
				return ite.next();
			}
			public boolean hasMoreElements() {
				return ite.hasNext();
			}
		};
		SequenceInputStream sis = new SequenceInputStream(e);
		FileOutputStream fos = new FileOutputStream("d2.txt");
		byte []buf = new byte[1024]; int len ;
		while((len = sis.read(buf))!=-1)fos.write(buf,0,len);
		fos.close();sis.close();
		System.err.println("succeed");
	}

	private static void sequenceInputStreamTest1() throws IOException {
		InputStream s1 = new FileInputStream("a.txt");
		InputStream s2 = new FileInputStream("b.txt");
		SequenceInputStream sis = new SequenceInputStream(s1, s2);
		Vector<FileInputStream> v = new Vector<FileInputStream>();
		v.add(new FileInputStream("a.txt"));
		v.add(new FileInputStream("b.txt"));
		v.add(new FileInputStream("c.txt"));
		Enumeration<FileInputStream> e = v.elements();
		sis = new SequenceInputStream(e);
		byte[] buf = new byte[1024]; int len;
		FileOutputStream fos = new FileOutputStream("d1.txt");
		while((len = sis.read(buf))!=-1)fos.write(buf, 0, len);
		fos.close(); sis.close();
		System.err.println("succeed");
	}
}
